//
//  JCCForgetPasswordViewController.swift
//  剂查查
//
//  Created by xianquan on 2024/12/12.
//  Copyright © 2024 shipin. All rights reserved.
//

import CommonTools
import TYUIKit
import YYText

class JCCForgetPasswordViewController: BaseViewController {
    
    var phone: String = ""
    
    var authCode: String = ""
    
    var pwd: String = ""
    
    var rePwd: String = ""
    
    var allowPravicy = false

    override func viewDidLoad() {
        super.viewDidLoad()
        setTitle("")
        setupUI()
    }

    func setupUI() {
        
        let logoIv = UIImageView(image: UIImage(named: "jcc_register_logo"), in: view) { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(TY_NaviBarHeight() + 16)
            make.width.equalTo(133)
            make.height.equalTo(57)
        }
        
        let phoneView = InputView(type: .phone) {[unowned self] text in
            phone = text
        }
        view.addSubview(phoneView)
        phoneView.snp.makeConstraints { make in
            make.top.equalTo(logoIv.snp.bottom).offset(76)
            make.leading.equalTo(37.5)
            make.trailing.equalTo(-37.5)
            make.height.equalTo(45)
        }
        
        let authView = InputView(type: .authCode) {[unowned self] text in
            authCode = text
        }
        view.addSubview(authView)
        authView.snp.makeConstraints { make in
            make.top.equalTo(phoneView.snp.bottom).offset(13)
            make.leading.trailing.height.equalTo(phoneView)
        }
        
        authView.authCallback = {[unowned self] tf, sender in
            let phoneNum = phone
            if !phoneNum.validate(.phoneNum) {
                toast(message: "请填写正确的手机号！")
                return
            }
            tf.becomeFirstResponder()
            NetworkRequest.request(networkType: .getAuthCode(phone: phoneNum)) { result in
                switch result {
                case .success:
                    XWLog(value: "获取验证码成功")
                    sender.beginCountdown()
                    sender.isEnabled = false
                case .failure(let error):
                    XWLog(value: "获取验证码失败:\(error)")
                }
            }
        }
        
        let pwdView = InputView(type: .password) {[unowned self] text in
            pwd = text
        }
        view.addSubview(pwdView)
        pwdView.snp.makeConstraints { make in
            make.top.equalTo(authView.snp.bottom).offset(13)
            make.leading.trailing.height.equalTo(phoneView)
        }
        
        let rePwdView = InputView(type: .rePassword) {[unowned self] text in
            rePwd = text
        }
        view.addSubview(rePwdView)
        rePwdView.snp.makeConstraints { make in
            make.top.equalTo(pwdView.snp.bottom).offset(13)
            make.leading.trailing.height.equalTo(phoneView)
        }
        
        let leftMargin = 37.5
        
        let unCheckImage = UIImage(named: "login_pravicy_uncheck")
        let checkedImage = UIImage(named: "login_pravicy_checked")
        let checkBoxBtn = UIButton(image: unCheckImage, title: nil, titleColor: nil, font: 0, in: view) { make in
            make.leading.equalTo(leftMargin)
            make.top.equalTo(rePwdView.snp.bottom).offset(adapt(16))
            make.width.height.equalTo(adapt(11))
        }
        checkBoxBtn.ty_hitExtend = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        
        checkBoxBtn.addBlock(for: .touchUpInside) {[unowned self] sender in
            guard let sender = sender as? UIButton else {return}
            sender.isSelected = !sender.isSelected
            allowPravicy = sender.isSelected
            sender.setImage(sender.isSelected ? checkedImage : unCheckImage, for: .normal)
        }
        
        let content = "已同意 隐私协议 和 用户协议 "
        let att = NSMutableAttributedString(string: content)
        att.yy_font = .systemFont(ofSize: adapt(12))
        att.yy_color = .black9
        addPravicyAtt(att: att)
        
        let size = att.sizeOfAttributedString(contentSize: CGSize(width: screenWidth() - leftMargin * 2 - adapt(25), height: 9999))
        let pravicyLabel = YYLabel(font: UIFont.systemFont(ofSize: 12, weight: .medium), textColor: nil, in: view) { make in
            make.leading.equalTo(checkBoxBtn.snp.trailing).offset(adapt(5))
            make.trailing.equalTo(-leftMargin)
            make.top.equalTo(checkBoxBtn).offset(-2)
            make.height.equalTo(size.height + 1)
        }
        pravicyLabel.numberOfLines = 0
        pravicyLabel.attributedText = att
        
        
        let resetBtn = UIButton(image: nil, title: "重置密码", titleColor: .white, font: 15.regular, in: view) { make in
            make.leading.equalTo(41)
            make.trailing.equalTo(-41)
            make.top.equalTo(pravicyLabel.snp.bottom).offset(30)
            make.height.equalTo(50)
        }
        resetBtn.setBackgroundColor(.selectedColor, for: .normal)
        resetBtn.cut(withRadius: 25)
        resetBtn.addBlock(for: .touchUpInside) {[unowned self] _ in
            if !allowPravicy {
                toast(message: "请同意隐私协议及用户协议")
                return
            }
            if !phone.validate(.phoneNum)  {
                toast(message: "请输入正确手机号")
                return
            }
            if !authCode.validate(.authCode) {
                toast(message: "请输入正确验证码")
                return
            }
            if !pwd.validate(.password) || !rePwd.validate(.password) {
                toast(message: "密码至少8位且包含数字，字母")
                return
            }
            if pwd != rePwd {
                toast(message: "密码不一致")
                return
            }
            NetworkRequest.request(networkType: .resetPwd(phone: phone, verify: authCode, password: pwd, password_confirm: rePwd)) { result in
                switch result {
                case .success(let response):
                    XWLog(value: "重置密码成功")
                    toast(message: "密码重置成功")
                case .failure(let error):
                    XWLog(value: "重置密码失败：\(error)")
                    toast(message: "密码重置失败")
                }
            }
        }
        
        let backBtn = UIButton(image: nil, title: "返回登录", titleColor: .black3, font: 14.regular, in: view) { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(resetBtn.snp.bottom).offset(10)
            make.height.equalTo(50)
        }
        
        backBtn.addBlock(for: .touchUpInside) {[unowned self] _ in
            navigationController?.popViewController(animated: true)
        }
        
    }
    
    func addPravicyAtt(att: NSMutableAttributedString){
        let arr: [(String, PvivacyType)] = [("隐私协议", .privacy), ("用户协议", .user)]
        for (str, type) in arr {
            att.yy_setTextHighlight(att.string.nsranges(of: str).first ?? NSRange(), color: UIColor(hex: "#497DE3"), backgroundColor: .selectedBg) { view, attStr, range, rect in
                showPrivacy(type: type)
            }
        }
    }

}


extension JCCForgetPasswordViewController {
    
    class InputView: UIView {
        
        var authCallback: (UITextField, CountdownButton)->() = {_, _ in}
        
        init(type: InputType, callback: @escaping (_ text: String) -> ()) {
            super.init(frame: .zero)
            
            backgroundColor = UIColor(hex: "#F6F7FB")
            
            let iv = UIImageView(image: UIImage(named: type.iconName), in: self) { make in
                make.leading.equalTo(17)
                make.centerY.equalToSuperview()
                make.width.equalTo(16.5)
                make.height.equalTo(20.5)
            }
            
            let isNum = type == .authCode || type == .phone
            
            let tf = UITextField(font: 14.regular, textColor: .black3, text: "", placeholder: type.placeholder, pattern: isNum ? .num : .notCn, maxLength: type.maxLength, in: self) { make in
                make.leading.equalTo(iv.snp.trailing).offset(10)
                make.centerY.equalToSuperview()
                make.trailing.equalTo(-17)
            } _: { text in
                callback(text)
            }
            tf.isSecureTextEntry = !isNum
            tf.keyboardType = isNum ? .numberPad : .asciiCapable
            if !isNum {
                tf.textContentType = .newPassword
            }
            
            if type == .authCode {
                let authBtn = CountdownButton(image: nil, title: "验证码", titleColor: UIColor(hex: "#942A2A"), font: 15.regular, in: self) { make in
                    make.trailing.equalTo(-15)
                    make.centerY.equalToSuperview()
                }
                authBtn.addBlock(for: .touchUpInside) {[unowned self] sender in
                    guard let sender = sender as? CountdownButton else {return}
                    authCallback(tf, sender)
                }
            }

        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    enum InputType {
        case phone
        case authCode
        case password
        case rePassword
        
        var placeholder: String{
            switch self {
            case .phone:
                "请输入手机号"
            case .authCode:
                "请输入验证码"
            case .password:
                "请输入新密码"
            case .rePassword:
                "二次输入密码"
            }
        }
        
        var maxLength: Int {
            switch self {
            case .phone:
                11
            case .authCode:
                6
            case .password:
                100
            case .rePassword:
                100
            }
        }
        
        var iconName: String {
            
            switch self {
            case .phone, .authCode:
                "jcc_login_phone"
            case .password, .rePassword:
                "jcc_login_password"
            }
        }
    }
}

